package com.yaowk.file;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.xiaoleilu.hutool.crypto.digest.DigestUtil;
import com.xiaoleilu.hutool.io.FileUtil;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.yaowk.common.constant.ServiceCode;
import com.yaowk.common.controller.BaseController;
import com.yaowk.file.model.File;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @authc yaowk
 * 2017/7/24
 */
public class FileController extends BaseController {

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd/");
    private static String baseFilePath = PropKit.use("config.properties").get("uploadFilePath");
    private static String baseUrlPath = PropKit.use("config.properties").get("uploadUrlPath");

    public void validator() {
        String md5 = getPara("md5").toLowerCase();
        Long size = getParaToLong("size");
        File file = File.dao.findFirst(Kv.by("md5 = ", md5).set("size = ", size));
        if (ObjectUtil.isNotNull(file)) {
            renderJson(file);
        }
        renderSuccess();
    }

    @Before(Tx.class)
    public void upload() {
        UploadFile uploadFile = getFile();
        if (ObjectUtil.isNotNull(uploadFile)) {
            try {
                String path = format.format(new Date()) + uploadFile.getFileName();
                java.io.File upFile = new java.io.File(baseFilePath + path);
                FileUtil.move(uploadFile.getFile(), upFile, false);
                File file = new File();
                file.setMd5(DigestUtil.md5Hex(FileUtil.readBytes(upFile)))
                        .setSize(upFile.length())
                        .setUrl(baseUrlPath + path)
                        .setType(uploadFile.getContentType())
                        .save();
                file.put("real_path", upFile.getAbsolutePath());
                renderJson(file);
                return;
            } catch (IOException e) {
                LogKit.error("", e);
            }

        }
        renderFail(ServiceCode.ERROR, null);
    }
}
